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END PUBLIC KEY-----';
    
    /*
     * 公钥加密
     */
    static public function publicEncrypt($data) {
//        $encryptData = openssl_public_encrypt($data, $encrypted, self::publicKey);
//        if($encryptData === false){
//            return "加密失败!";
//        }
//        $encodeData = base64_encode($encrypted);
//        return $encodeData;
        // $data1 = base64_encode($data);
        $encrypted = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_public_encrypt($chunk, $encryptData, self::publicKey, OPENSSL_PKCS1_PADDING);
            $encrypted .= $encryptData;
            
        }
        
        $encodeData = base64_encode($encrypted);
        return $encodeData;
    }

    /*
     * 公钥解密
     */
    static public function publicDecrypt($data) {
        $decodeData = base64_decode($data);
        $decrypted = '';
        foreach (str_split($decodeData, 256) as $chunk) {
            openssl_public_decrypt($chunk, $decryptData, self::publicKey, OPENSSL_PKCS1_PADDING);
            $decrypted .= $decryptData;
        }
        return $decrypted;
    }

    /*
     * 私钥加密
     */
    static public function privateEncrypt($data) {
        $encrypted = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_private_encrypt($chunk, $encryptData, self::publicKey, OPENSSL_PKCS1_PADDING);
            $encrypted .= $encryptData;
        }
        $encodeData = base64_encode($encrypted);
        return $encodeData;
    }

    /*
     * 私钥解密
     */
    static public function privateDecrypt($data) {
//        $decodeData = base64_decode($data);
//        $decryptData = openssl_private_decrypt($decodeData, $decrypted, self::privateKey);
//        if($decryptData === false) {
//            return "解密失败!";
//            
//        }
//        return $decrypted;

        $decodeData = base64_decode($data);
        $decrypted = '';
        foreach (str_split($decodeData, 256) as $chunk) {
            openssl_private_decrypt($chunk, $decryptData, self::privateKey,  OPENSSL_PKCS1_PADDING);
            $decrypted .= $decryptData;
        }
        return $decrypted;
    }
}